ColdFusion Article

Employee Updater: Building a Client-Server Application with Macromedia Flash Data Connection Wizard and ColdFusion

Ben Forta

www.forta.com

Macromedia Flash has been a capable client computing platform for quite some time, and ever since Macromedia Flash MX, integration with ColdFusion has been clean and simple. But recently released Macromedia Flash MX Professional 2004 Wizards make the process of building ColdFusion-powered Flash applications easier than ever, as this article will demonstrate.

Note: This article assumes a good working knowledge of ColdFusion, use of ColdFusion MX, and basic familiarity with ColdFusion Components.

Some Basics

For many of us, the word "Flash" still conjures up images of slow downloads, often extraneous animation, overly intrusive pop-up ads, and "Skip Intro." That's a shame. While Flash has proven itself invaluable in the graphics and design department, and indeed that is where its origins lie, Flash player can do so much more. In fact, since the release of Flash MX (and now with Flash MX Professional 2004), developers from a variety of backgrounds are discovering that Flash has legitimate and unparalleled value in application development in general.

The Flash player runs Flash files (SWF files), which you create using the Flash IDE (lots of uses of the word Flash, and thus, frequent confusion as to what exactly we're referring to at any given time). Players are available for all sorts of operating systems and devices and platforms, and the same SWF files run in exactly the same way on each. This makes Flash a very compelling alternative to HTML and DHTML, which is anything but portable. In addition, as the Flash player is a thin-but-not-as-thin-as-the-browser client, the player is capable of so much more than plain old HTML (even HTML plus client-side scripting).

But Flash runs on the client, not on the server. Flash therefore cannot access databases on the server, and cannot generate e-mail messages or authenticate user logins. All of these require communication between Flash on the client and a back-end server. And Macromedia has built this capability—being able to communicate to back-end servers—right into Flash player.

As such, you can use Flash as a client in client-server style development, both as an alternative to specific elements in an HTML page, and as a replacement for complete HTML application front ends.

Note: To follow along you'll need to be running Flash MX Professional 2004 with the latest updates and wizards installed. See more in the Getting Set Up section.

What You'll Build

The best way to understand Flash applications and how they relate to ColdFusion is to build a sample application. This article does not cover every Flash feature and option and only uses a few of the included components; refer to the included documentation for complete component coverage and extensive examples. Having said that, I'll guide you through building a complete application. The application will be a data-entry front end for a user database and will feature:

  • A data grid for browsing and scrolling through a list of users
  • A related data grid with a master/detail view
  • Integrated user login processing
  • The ability to edit existing users and to insert and delete users
  • Batch database updating

…all without browser screen refreshes!

Ready? Great, we're about to begin, but first some setup details.

Requirements

To complete this tutorial you will need to install the following software and files:

ColdFusion MX Standard, Enterprise, or Developer Edition

  • Install the example applications (the database this tutorial uses the same database as the example applications).
  • Apply the latest ColdFusion updater

Flash MX Professional 2004

A couple of important notes on your Flash installation:

  • Install the Flash MX Professional 2004 patches and updates. In particular, make you have the Flash MX Professional 2004 updater released on November 10, 2003.
  • You need to have professional version of Flash. If you need to upgrade your Flash MX 2004 version to Flash MX Professional 2004, Open Flash MX 2004 and go to Help > Upgrade to Flash MX Professional 2004. Click Continue to try or buy Macromedia Flash MX Professional 2004 and enter a serial number. You must quit and restart Flash MX Professional 2004 again for the upgrade to take effect.

Dreamweaver MX 2004

Data Connection Wizard and DataGrid Column Editor Extensions

You can download the Data Connection Wizard and DataGrid Column Editor extensions from Macromedia Exchange. Here's how you get them:

Before installing the extensions, download and install the most recent Extension Manager.

Download the following extensions:

Tutorials and sample files:


The sample files in ZIP contain the complete code for this application. Instead of using the solution files for this application, I suggest you build the code along with me. I'll tell you when you need to refer to the solution files near the end of this tutorial.

Completing the Installation

To ensure that you have installed the extensions, open any Flash document in Flash MX Professional 2004. Go to the Commands menu. If the they are installed, you'll see a menu option called Data Connection Wizard. For this tutorial, you use the DataGrid Column editor through the Data Connection Wizard and therefore it does not appear in the Commands menu.

If you have all the software installed, continue with these steps:

  1. Create a new folder called cfflash under your webroot for the application. The instructions provided here assume that you'll be using ColdFusion MX with the integrated HTTP server on port 8500.
  2. Create a ColdFusion file named employees.cfc in your cfflash application directory. You'll add methods to this file shortly.

The Back-End ColdFusion Web Service

For the application to obtain a list of users and a list of departments, create two CFC methods, named ListDepts and ListByDept, which will return the lists. Copy and paste the following code in employees.cfc in Code view:

<CFCOMPONENT>
<!--- Obtain department list --->
<CFFUNCTION NAME="ListDepts"
            HINT="List departments"
            ACCESS="remote"
            RETURNTYPE="query">
   <CFQUERY DATASOURCE="exampleapps"
            NAME="dept">
   SELECT *
   FROM tblDepartments
   ORDER BY DepartmentName
   </CFQUERY>

   <CFRETURN dept>
</CFFUNCTION>

<!--- Obtain department employees --->
<CFFUNCTION NAME="ListByDept"
            HINT="Get employee"
            ACCESS="remote"
            RETURNTYPE="query">
   <CFARGUMENT NAME="DepartmentID"
               TYPE="string"
               REQUIRED="yes">
   <CFQUERY DATASOURCE="exampleapps"
            NAME="emps">
   SELECT *
   FROM tblEmployees
   WHERE DeptIDFK = '#ARGUMENTS.DepartmentID#'
   ORDER BY LastName, FirstName
   </CFQUERY>

   <CFRETURN emps>
</CFFUNCTION>
<CFCOMPONENT>

The ListDepts method retrieves a list of departments from the tblDepartments table. The ListByDept method returns all the employees in a specified department from the tblEmployees table. Save both of these methods in employees.cfc. You'll add more methods to this component later; for now this is all the ColdFusion code you need.

Notice that both methods specify ACCESS="remote". You must use this attribute is required for Flash on the client to be able to invoke CFC methods on the server. The default ACCESS level is public, which allows any code on the server to access the CFCs, but not any code outside of the server. Setting ACCESS="remote" for specific methods makes those methods available remotely (to Flash, in this example).

Testing the Back-End Code

Before going further, verify that the ColdFusion component functions properly. Debugging CFML problems from the Flash client side gets rather complicated; as a rule always test your back-end code independently first.

The following simple CFML code invokes the employees.cfc component to display a list of departments and lets a user click a department to display department members.

<!--- Instantiate employee component --->
<CFOBJECT COMPONENT="employees" NAME="empObj">

<!--- Get departments --->
<CFSET depts=empObj.ListDepts()>

<H1>Departments</H1>
<UL>
   <CFOUTPUT QUERY="depts">
      <LI><A HREF="emplist.cfm?departmentid=#DepartmentID#&departmentname=#DepartmentName#">#DepartmentName#</A></LI>
   </CFOUTPUT>
</UL>

<!--- Employees, if department id was passed --->
<CFIF IsDefined("URL.DepartmentID")
      AND IsDefined("URL.DepartmentName")>
   <!--- Get employees --->
   <CFSET emps=empObj.ListByDept(URL.DepartmentID)>
   <CFOUTPUT>
   <H1>#URL.DepartmentName# Employees</H1>
   </CFOUTPUT>
   <UL>
   <CFOUTPUT QUERY="emps">
      <LI>#LastName#, #FirstName#</LI>
   </CFOUTPUT>
   </UL>
</CFIF>

Save this code in a new file named emplist.cfm in the application directory, and run it to verify that the CFC functions (your output will be similar to Figure 1). You are now ready to build a Flash front end to this same ColdFusion component.

HTML version of the employee by department application

Figure 1. HTML version of the "employee by department" application

Preparing Flash

Use the following steps to prepare Flash.

  1. Start Flash MX Professional 2004. Create a Flash Form Application by selecting File > New > Flash Form Application.
  2. Save the file as employees.fla in the cfflash application directory.
  3. Flash Form Applications comprise multiple screens that you can display and hide. The screens (forms) appear in a tree view to the left of the Stage. By default, Flash names the top level form application, and creates a child form named form1. Double-click the child form name and rename it data, as this form will contain the data grids. Your screen will look like Figure 2.
  4. Save the changes.
Flash Forms applications are made up of multiple screens (forms) arranged in an hierarchical view

Figure 2. Flash Forms Applications are made up of multiple screens (forms) arranged in an hierarchical view

Before you can use the ColdFusion component you just created, Flash needs to know about it (the CFC's name, location, method details, and more). To register the ColdFusion component with Flash, follow these steps:

  1. Select Window > Development Panels > Web Services to display the Web Services panel (Figure 3).

    Registered Web Services are listed in the Web Services panel

    Figure 3. Registered web services are listed in the Web Services panel

  2. Click the Define Web Services button (the globe icon) to display the Define Web Services dialog box.
  3. Click the Plus (+) button to add a new web service, and then provide the URL to the CFC you just created. If you are using ColdFusion's integrated HTTP server on the default port 8500 and the cfflash path in the steps above, then the URL will be http://localhost:8500/cfflash/employees.cfc?wsdl (see Figure 4). Click OK.

    Web Services must be registered before they may be used in the Wizards

    Figure 4. Register a web service before using it in the wizards.

  4. Flash connects to the specified URL to obtain CFC information; it then returns to the previous screen displaying the newly defined web service (the CFC).
  5. Close the Web Services panel.

Building the Flash Departments Grid

The Flash application you'll create will have two data grids, one on top of the other. The upper grid will display the departments, and each time a user clicks a department, the lower grid will display the department employees.

Creating a data-driven grid requires using three Flash components: the grid itself; the WebServiceConnector component, which communicates with the ColdFusion component; and a DataSet, which binds the two providing other Flash components and code with access to retrieved data. You could manually drag these three components from the Flash Components panel to the Stage, provide the required properties, and then bind them together. Or you can use the Data Connection Wizard to do much of the work for you. Here are the steps to follow:

  1. Select Commands > Data Connection Wizard. This launches the wizard (Figure 5).

    The Data Connection Wizard is used to simplify connecting to Web Services and XML data

    Figure 5.The Data Connection Wizard simplifies connecting to web services and XML data

  2. The dialog box will ask you to specify a data source, select Web Service from the pop-up menu, and the wizard will display a list of registered web services (including the one you just registered).
  3. Expand the service employeesService to display its methods.
  4. Expand the ListDepts method to display its attributes and results.
  5. Click Results. (You will use the results of ListDepts to populate the grid.)
  6. Click Next.
  7. At this point, you might expect to see a list of data fields available in the results, but you won't if you're using ColdFusion. Since ColdFusion queries are dynamic and are not evaluated until runtime, there is no way that the wizard can display the list of fields; you must specify them manually. Click Next.
  8. In this wizard step, you can add, update, and remove fields. Click the Add Field button and add a field named DEPARTMENTID with a data type of String (ColdFusion query columns must be uppercase).
  9. Add a second text field and name it DEPARTMENTNAME with a data type of String (Figure 6).

    If using a ColdFusion Component, field names must be specified manually

    Figure 6. If using a ColdFusion Component, field names must be specified manually

  10. Click Next to go to the final wizard screen.
  11. You must name component instances in Flash. Specify dept as the Label for Generated Components. Leave the two checkboxes selected (the first instructs the wizard to create a data grid, and the second embeds a button that a user may click to execute the web service call) as in Figure 7.

    The Wizard can create optional DataSets and trigger buttons

    Figure 7. The wizard can create optional DataSets and trigger buttons.

  12. Click Finish to complete the wizard.

You should now have four components on the Stage: a WebServiceConnector, a DataSet, a DataGrid, and a Button. Click any of the first three and look at the tabs in the Component Inspector panel. These are the values that you would have had to specify manually were it not for the Data Connection Wizard. (You will have to use the Component Inspector panel later).

Now test the application:

  1. Save your changes with File > Save.
  2. Select Control > Test Movie to launch the application.
  3. An empty grid will display. To populate the grid, click the Get Data button; Flash will connect to ColdFusion through the WebServiceConnector, retrieve the data from the ColdFusion component ListDepts method, and use the results to populate the DataSet, which populates the DataGrid (Figure 8).

    A working DataGrid, no code used

    Figure 8. A working DataGrid, no code used

  4. To stop testing the application, close the file by clicking the Close (X) button at the top right of the Flash application window. (Don't click the Close button on the Flash title bar, that will exit Flash).

Not bad at all—for no lines of code that is.

Finishing the Departments Grid

The default grid is too big—it leaves no room for or next grid—so set the size and position:

  1. Moving the grid may cover up the icons for the WebServiceConnector and DataSet components, so drag all of those to the edge of the Stage. (They have no visual interface, so in truth it makes no difference where you locate them.)
  2. Select deptDataGrid. Make sure you select the data form in the forms tree.
  3. If the Properties panel is not open, open it (Figure 9).

    Control size and position is defined in the Properties panel

    Figure 9. Control size and position is defined in the Property inspector.

  4. Set the position and size in the Property inspector as follows: W=510, H=150, X=20, Y=20.
  5. Close the Property inspector if you need the screen space.

Before moving on to the next data grid, make two changes in the department grid; right now, the interface displays both the department name and id, when you only need to display the department name. Moreover, your grid should populate dynamically without requiring the user to press a button.

You'll tackle the displayed columns first. By default, data grids display all columns in their related data sets; to change this behavior, use ActionScript code. Fortunately, a wizard can generate this code for you. Follow these steps:

  1. Select deptDataGrid. (Make sure you select the data form in the forms tree.)
  2. If the Component Inspector panel is not open, open it.
  3. Click the wizard button (the yellow star icon) on the top right of the panel, and select DataGrid Column Editor to launch a wizard (Figure 10).

    The DataGrid Column Editor Wizard generates grid layout code

    Figure 10. The DataGrid Column Editor wizard generates grid layout code.

  4. Use the wizard to define the columns you want to display in a grid and the properties for each column. You can manually enter columns by clicking the Plus (+) button, or you can import them from the associated DataSet. Click the Import Columns button to import the DataSet columns; you'll see both DEPARTMENTID and DEPARTMENTNAME listed.
  5. To prevent DEPARTMENTID from displaying, select it, and click the Minus (–) button.
  6. DEPARTMENTNAME (all in capitals) does not make an ideal grid column header, so, in the Column Label field, type Department. Make sure to deselect the Editable checkbox and setWidth to 500. (This fills the entire width of the grid.)
  7. Click OK. The Wizard will generate about 20 lines of ActionScript code that define the grid columns (just the one column in this example). Click OK again.
  8. Save your changes and select Control > Test Movie to launch the application. Your revised grid appears in its correct location and with just one column (Figure 11).

    To include, exclude, or format grid columns, ActionScript code must be used

    Figure 11. To include, exclude, or format grid columns, use ActionScript code.

The final change is to delete the Get Data button and to write some code to force the grid to populate automatically upon starting. Here are the steps:

  1. Select the Get Data button. (Make sure that you select the data form in the forms tree.)
  2. Delete the Get Data button by pressing Delete on your keyboard.
  3. You must place the code for automatically populating the grid with the data form selected, taking care that you haven't selected any of the controls within it. Click any empty space on the Stage and make sure that the tab at the bottom of the Actions panel reads data.
  4. Type the following code in the Actions panel:

    // Populate grid on startup
    on (reveal) {
       deptReceiveWebServiceConnector.trigger();
    }
    
  5. Save your changes and select Control > Test Movie to launch the application. The application will load as before, but this time the grid will populate without the user needing to press a button.

The code you type warrants some explanation. Flash supports events, and code associated with those events executes when certain events occur. In this case, the on(reveal) event instructs Flash to execute the following code when the current form (the data form) reveals or displays itself. The deptReceiveWebServiceConnector.trigger() event simply triggers or executes the deptReceiveWebServiceConnector service. This is exactly what the Get Data button performed.

Building the Employees Grid

Next, you'll create the employees grid; this will display the employees in the department selected in the first grid. Once again, start with the wizards:

  1. Select the data form.
  2. Select Commands > Data Connection Wizard to launch the wizard.
  3. Select Web Service as the Type of Data Source.
  4. Select employeesService, and expand the ListByDept method to display its attributes and results.
  5. Click Results (as you will use the results of ListByDept to populate the grid).
  6. Click the Next button.
  7. A warning box appears to let you know that this method requires a parameter that you have not yet defined. (You must pass the department to the method for the method to retrieve the correct employee list.) Click OK for now; you'll provide this data later.
  8. Once again, no data fields will display, so click Next.
  9. Add the following fields:
    1. FIRSTNAME with a data type of string
    2. LASTNAME with a data type of string
    3. TITLE with a data type of string
    4. EMAIL with a data type of string
    5. STARTDATE with a data type of date, a source data format of YYYY MM DD (the format data is returned from ColdFusion), and a display format of MM-DD-YYYY (unless you prefer another of the available formats, as this has no impact on the data itself and just affects the formatting in the grid)
    6. EMPLOYEEID with a data type of string
    7. DEPTIDFK with a data type of string
  10. Click Next to go to the final wizard screen.
  11. Specify emp (as in employee) as the name in the Label for Generated Components. Leave the first checkbox selected, but deselect the second checkbox. (You don't want to create a button.)
  12. Click Finish to complete the wizard.

You must reposition the grid::

  1. Drag the new WebServiceConnector and DataSet icons out of the way (the lower right of the Stage will work well).
  2. Select the new data grid (named empDataGrid) and set the position and size in the Property inspector as follows: W=510, H=175, X=20, Y=180 (Figure 12).

    Use the Properties panel to precisely position controls

    Figure 12. Use the Property inspector to precisely position controls.

  3. Save your changes, and then select Control > Test Movie to launch the application.

The application will run and display the new grid, but that grid will not be populated because the app never executes the second web service. To execute the web service, you must first pass the appropriate department id to the method:

  1. Select the empReceiveWebServiceConnector icon.
  2. Open the Component Inspector panel (if it is not already open).
  3. Select the Bindings tab, you'll see one binding defined (connecting the results returned by the web service call to the DataSet).
  4. Click the Plus (+) button to add a binding; this will display the Add Binding dialog box.
  5. Available bindings are grouped into params, data sent to a web service call; and results, data that a web service call returns. You need to pass the department id to the method; select the DepartmentID param and click OK.
  6. The new binding will now appear in the Bindings tab in the Component Inspector panel, but it is not bound to anything yet. To bind it, select it, and click the bound to row below.
  7. Click the magnifying glass button to display a list of available binding selections.
  8. Options in the Bound To dialog box display hierarchically. Bind to the currently selected department id in the department DataSet by locating the deptDataSet and selecting it; then select DEPARTMENTID from the list on the right (Figure 13).

    The Bound To dialog is used to interactively select data bindings

    Figure 13. The Bound To dialog is used to interactively select data bindings

  9. Click OK and the new binding will appear in the Component Inspector panel. Now, whenever your SWF executes the method, it also passes the selected department id to the method.

You must execute the ListByDept each time the selection in deptDataSet changes. Do so with the following steps:

  1. Select deptDataSet on the Stage. You can verify which control you have selected by looking at the Property inspector or at the tab at the bottom of the Actions panel.
  2. Type the following code in the Actions panel:

    // Get employees when department is selected
    on (iteratorScrolled) {
       _parent.empReceiveWebServiceConnector.trigger();
    }
    
  3. Save your changes and then select Control > Test Movie to launch the application. The application will load as before, but this time selecting any department displays the department employees in the lower grid.

The iteratorScrolled event executes each time the selection in a DataSet changes. The code here executes the empReceiveWebServiceConnector web service. The _parent is necessary because references are all relative. The DataSet and the WebServiceConnector are both children of the data form, so _parent refers to the form, and empReceiveWebServiceConnector then refers to the connector within it. It is worth noting that the following code would have worked too:

// Get employees when department is selected
on (iteratorScrolled) {
   _root.application.data.empReceiveWebServiceConnector.trigger();}

The _root refers to the top of the application tree; application is the top level form; data is a child of application, and empReceiveWebServiceConnector is a child of data. The result is identical, the only difference is that this code uses absolute addresses whereas the previous example uses relative addresses. To keep the steps simple, I did not use the DataGrid Column Editor wizard, causing all the columns to display using the column names as headers. You may use the wizard if you desire to modify the format; for instance, the finished app probably should not display the EMPLOYEEID and DEPTIDFK columns (as a user should never see or edit these).

Creating the Login Screen

So far you have a working application which displays a master/detail view of two related tables, without typical browser refreshes. That is pretty impressive in and of itself. But more impressive would be the ability to add, edit, and delete records all from within the grid.

The truth is, to make a Flash grid editable is really easy. For instance, editable is a grid property; just set it to true and you have an editable grid. But you'd probably not want every user to be able to edit data, and so next you'll implement a login screen. All users will be able to browse data, but edits will require a log-on.

The first thing you'll do is create the login screen. Here are the steps:

  1. Add a new form to the application by clicking the Plus (+) button in the form tree control.
  2. This new form will contain the login screen. Double-click the default name and change it to login (Figure 14).

    Each form in a form application must be uniquely named

    Figure 14. Each form in a form application must be uniquely named.

  3. Now add some form components to the login screen. Drag a Label component from the Components panel onto the Stage. Open the Property inspector (select the Parameters tab) and set W=100, H=22, X=30, Y=20. Then select the text field (in the Property inspector Parameters tab) and enter the text Login:.
  4. Place another Label component on the Stage. Set W=100, H=22, X=30, Y=50. Then select the text field and enter the text Password:.
  5. Drag a TextInput component onto the Stage. In the Property inspector name the instance loginName. Set W=100, H=22, X=145, Y=20.
  6. Drag another TextInput component onto the Stage. In the Property inspector name the instance loginPassword. Set W=100, H=22, X=145, Y=50. Click the password field and set it to true. You make it a password field so that when a user types a password, it does not appear on screen.
  7. Drag a Button component onto the Stage. In the Property inspector, name the instance loginButton. Set W=100, H=22, X=35, Y=85. Click the label field and set it to Login.
  8. Drag another Button component onto the Stage. In the Property inspector name the instance cancelButton. Set W=100, H=22, X=140, Y=85. Click on the label field and set it to Cancel. Your form will look like Figure 15.
  9. You now have a complete form (you'll wire it up shortly). For now, save the changes and test the application.

    The login form contains two labels, two input controls, and two buttons

    Figure 15. The login form contains two labels, two input components, and two buttons.

    Flash Forms are transparent, and will show through each other by default

    Figure 16. Flash Forms are "transparent," and will show through each other by default.

You'll find that the application works, actually, a bit too well. A seen in Figure 16, the new login form displays automatically on startup and overlays the grids; obviously, that is not the correct behavior. By default, all new forms will display when the application starts. To prevent the login form from initially displaying, do the following:

  1. Click the login form in the form tree.
  2. Open the Property inspector and ensure that you've selected the Parameters tab.
  3. Select the visible parameter, and set it to false.
  4. Save and test the application, now the form will not automatically display when it starts; although there is no way to make it appear yet, you'll learn how to fix that next.

When working with multiple forms, here's a useful tip: Right-click any form in the tree and select Hide Screen to prevent it from appearing while you work on other forms. This has no impact on runtime execution, it only affects visibility within the Flash authoring tool.

You must display a login screen only when you need a log-on. You'll add a login button and display the login form when it a user requests information that requires a log-on. Here are the steps:

  1. Add another form to the application and name it navLogin; ensure that its visible parameter is true. (You want the login button to display on startup.)
  2. Select the navLogin form and add a Button component to it. In the Property inspector, name the instance buttonLogin. Set W=75, H=22, X=460, Y=370. Click the label field and set it to Login.
  3. Save the changes and run the application; you'll see the new Login button displayed (because it is on the form that is displaying). Clicking the button will not do anything yet, though.
  4. Click the new Login button (in the navLogin form), and open the Actions panel. The Actions panel should show buttonLogin in the ActionScript tab.
  5. Type the following code in the Actions panel (Figure 17):

    // Display login form
    on (click) {
      _root.application.login.visible=true;
    }
    
    Code in the Actions panel is associated with the selected form or control

    Figure 17. Flash associates code in the Actions panel with the currently selected form or component

  6. Save the changes and run the application. When a user clicks Login, your application will now display the form.

That worked—the form displayed, but the UI is clumsy. The grids show through the form, and users can use them while the login form appears. What you really want is for the form to display in a pop-up window. This is feasible, but requires some manual coding. Here is what you need to do:

  1. Go back to the Actions panel for the buttonLogin, remove the code you just inserted, and enter the following code instead:

    // Popup login form when button pressed
    on (click) {
       // Work out position
       var x = (_root.application.width-300)/2;
       var y = (_root.application.height-150)/2;
       // Create popup
       var loginWindow = mx.managers.PopUpManager.createPopUp(_root,
                       mx.containers.Window,
                       true,
     		   {contentPath:"login", title:"Login", _x:x, _y:y});
       // Set window size
       loginWindow.setSize(300, 150);
       // Save window instance (so it can be closed later)
       _root.application.login.loginInstance=loginWindow;
    }
    
  2. This code uses the Window component to create a pop-up window. (You'll learn more about the code in a moment.) If you were to run it as is, the form would not pop up because the Window component code would not be in the final compiled SWF file. Add the component to the SWF by dragging a Window component from the Components panel onto the Stage.
  3. Of course, you don't actually need the Window component on the Stage, so delete it. If that sounds a bit awkward, well, it is. Open the Library panel (Figure 18) if you are so inclined; it lists the components currently in use, and you'll see that it lists Window (even if you deleted it).

    Use the Library panel to see the controls used by an application

    Figure 18. Use the Library panel to see the components used by an application.

  4. Save your changes and test the application. When you press the Login button, the form will now display in a pop-up window.

So what does the ActionScript code that you just used actually do? The on(click) traps button clicks so that the code that follows will execute when a user presses Login. The first two lines of code define two variables, x and y, which contain the position of the pop-up window (calculated by taking the application height and width minus the pop-up window height and width divided by two). The next line of code uses the PopUpManager class to create a pop-up window, specifying login as the name of the form to load in the window, Login as the window title, and passing x and y variables for the position. Next, the code sizes the window and saves a reference to the window instance so that the SWF can close the window later on. You'll add login form processing in a moment; for now, you need, at the very least, a way to close the Login window.

The following steps add processing to the login form Cancel button:

  1. Select the login form.
  2. Select the Cancel button.
  3. Open the Actions panel, and enter the following code:

    // Close login window
    on (click) {
      _root.application.login.loginInstance.deletePopUp();
    }
    
  4. Save your changes and test the application. You will now be able to press the Login button to pop up the login form (Figure 19); click Cancel to close the pop-up window.

    Use Windows and the Popup Manager to create intuitive popup windows

    Figure 19. Use the Window component and the PopUpManager class to create intuitive pop-up windows.

Processing Logins

You now have a login form, which does nothing other than move and close. Next, you'll process the log-on. Validating the log-on requires a new method in the ColdFusion component. Copy the code for the Authenticate method to employees.cfc.

<CFFUNCTION NAME="Authenticate"
            HINT="Employee authentication"
            ACCESS="remote"
            RETURNTYPE="boolean">
   <CFARGUMENT NAME="LoginName"
               TYPE="string"
               REQUIRED="true">
   <CFARGUMENT NAME="LoginPassword"
               TYPE="string"
               REQUIRED="true">

   <CFSET var result=FALSE>

   <CFIF ARGUMENTS.LoginPassword IS "password">
      <CFSET result=TRUE>
   </CFIF>
	
   <CFRETURN result>
</CFFUNCTION>

The Authenticate method takes a login name and password, and returns true if the log-on authenticates and false if not. Although this particular method is stubbed for simplicity's sake, instead of doing a real lookup, it looks at the password and returns true if the password is password. In your own apps, you would obviously replace the processing in this method with your own database or LDAP lookups, or some other processing.

You need to make Flash aware of this new method, so use the following steps:

  1. Select Window > Development Panels > Web Services to display the Web Services panel.
  2. Click the Refresh button (the blue circular arrow icon). Flash will update the web services list and display the new Authenticate() method.

With that done, you can now wire up the login screen:

  1. Select the login screen.
  2. Drag a WebServiceConnector component from the Components panel to the login form. You might want to place it in the middle so it doesn't interfere with pop-up window placement.
  3. Select the new WebServiceConnector, open the Property inspector, and name the instance authService.
  4. Unlike the previous two web service calls, which the wizards populated, you'll need to configure this one manually. Open the Component Inspector panel, making sure that you select authService on the Stage.
  5. Select the Parameters tab. In the WSDLURL field, select the URL to the employees.cfc web service. If you're using the defaults, this will be http://localhost:8500/cfflash/employees.cfc?wsdl. In the operation field select Authenticate (Figure 20).

    Web Service properties may be manually defined in the Components Panel

    Figure 20. Define web service properties manually in the Components Inspector panel.

  6. The Authenticate web service requires that you pass two parameters to it: the login name and password. Therefore, you must bind the two form fields in the login form to this web service. Select the Bindings tab, click the Plus (+) button to display the Add Binding dialog box, select LoginName, and click OK to add it as an available binding.
  7. Click the Plus (+) button again, and add LoginPassword as an available binding.
  8. Select the LoginName binding, click the bound to field, and then click the magnifying glass to display the Bound To dialog.
  9. Locate the login form, select the loginName TextInput, click the text field on the right (Figure 22), and click OK to bind the loginName field to the LoginName web service argument.

    When using the Bound To dialog, be sure to select the correct controls

    Figure 21. When using the Bound To dialog, be sure to select the correct components.

  10. Repeat the last two steps to bind the loginPassword TextInput field to the LoginPassword web service argument.

Now, when the authService web service executes, it will pass values from the two form fields to ColdFusion for processing. The only problem is that, as is, the web service will never execute on its own. You need to add code to the form's Login button so that it will execute the web service call when a user presses it. You can do it manually or use a simple wizard:

  1. Select the login form.
  2. Select the Login button.
  3. Open the Behaviors panel.
  4. Press the Plus (+) button. Select Data > Trigger Data Source to display the Trigger Data Source dialog box.
  5. Expand the tree to locate root > application > login > authService (see Figure 22).

    The Trigger Data Source behavior allows for the interactive selection of Web Services

    Figure 22. The Trigger Data Source behavior allows for the interactive selection of web services.

  6. Select authService and press OK. Flash will generate a few lines of code that will execute the authService web service call when a user clicks the Login button.

When a user runs the application now, clicking the Login button causes the login form to pop up, which asks the user for a name and password and authenticates him. But you've yet to tell Flash what to do when the Authenticate method returns true or false. Use the following steps to add this code:

  1. Select the login form.
  2. Select the authService WebServiceConnector component.
  3. Open the Actions panel and paste the following code:

    // Process authentication results
    on (result) {
      if (results) {
        // If returned true
        // Make employee data editable
        _root.application.data.empDataGrid.editable=true;
        // Close login popup
        _root.application.login.loginInstance.deletePopUp();
      }
      else {
        // Returned false, show error message
        mx.controls.Alert.show("Login Failed!", "Login");
      }
    }
    
  4. Save the application and test it. You should now be able to login using any login name and a password of password. Upon successful log-on, you can edit the employee DataGrid (Figure 23).

    The Flash DataGrid supports inline editing

    Figure 23. The Flash DataGrid supports inline editing.

Logging Out

Next, you'll create a logout button. To make it easy to switch between the login and logout buttons, and the buttons you'll add for insert, delete, and save, you''ll put the logout button on a separate form:

  1. Add another form to the application and name it navLogout.
  2. Select navLogout in the form tree and go to the Property inspector. Set the visible parameter to false. You do not want the Insert, Delete, Save, and Logout buttons to display on startup (before a user logs in).
  3. Select the navLogout form and add a Button component to it. In the Property inspector, name the instance buttonLogout. Set W=75, H=22, X=460, Y=370. Click the label field and set it to Logout.
  4. Click the new Logout button in the navLogout form and open the Actions panel.
  5. Type the following code in the Actions panel:

    // Process logout
    on (click) {
       // Hide logout buttons
       _root.application.navLogout.visible=false;
       // Show login button
       _root.application.navLogin.visible=true;
       // No more editable
       _root.application.data.empDataGrid.editable=false;
    }
    
  6. The above code ensures that upon log-out, the SWF hides the Logout button and displays Login button again. The opposite needs to occur upon log-on, so select the login form and the authService component, and insert the following two lines before the comment that reads // Close login popup:

    // Hide login buttons
    _root.application.navLogin.visible=false;
    // Show logout button
    _root.application.navLogout.visible=true;
    
  7. Save the changes and run the application. You should be able to log in and log out as needed. When you log in, the code lets you edit the employees in the grid and displays the Logout button; when you log out, the code prevents you from being able to edit and displays the Login button again.

Allowing Insert and Delete

Being able to edit data when you are logged in is very useful, but what if you wanted to add a new employee, or delete one? Doing so is actually very easy; here's how you add buttons for those functions:

  1. Select the navLogout form.
  2. Drag a Button component from the Components panel onto the Stage. In the Property inspector, name the instance buttonInsert. Set W=75, H=22, X=20, Y=370. Click the label field and set it to Insert.
  3. Drag another Button component onto the Stage. In the Property inspector, name the instance buttonDelete. Set W=75, H=22, X=100, Y=370. Click the label field and set it to Delete. Your screen should look like Figure 24.

    Placing buttons on a separate Form allows for them to be swapped in and out easily

    Figure 24. Placing buttons on a separate form lets you swap them in and out easily.

  4. Select buttonInsert and enter the following code in the Actions panel:

    // Process insert button
    on (click) {
       // Insert a row into the data set
       _root.application.data.empDataSet.addItem(
          {
             STARTDATE:new Date().getTime(),
             DEPTIDFK:_root.application.data.deptDataSet.DEPARTMENTID
          });
    
    
  5. Select buttonDelete and enter the following code in the Actions panel:

    // Process delete button
    on (click) {
       // Remove current item from data set
       _root.application.data.empDataSet.removeItem();
    }
    
  6. Save your changes and test the application. The user will be able to use the Insert and Delete buttons when he/she logs in to insert and delete employees.

The code that processes inserts uses the DataSet addItem() method to add an employee; it uses the currently selected department id for the department, and today's date as the STARTDATE. The code that processes deletes uses the DataSet removeItem() method to simply remove the currently selected item.

Note that you can enter an employee ID, but the CFC will create one and disregard the one you entered when it writes the information to the database on the server.

Managing Changes

Now you have a rather impressive application. It displays data from two tables, and, processing updates without page refreshes, it supports user login and logout, and when a user logs in, it lets the user insert, update, and delete data.

However, there is one big limitation with the current application. It makes data changes in the local DataSets within Flash and doesn't send them back to the server; therefore, the application doesn't update the back-end databases with users' changes. Handling updates requires the use of a special component called a Resolver. The Resolver's job is to track and resolve changes; it keeps a list of what changes the user has made, and then submits them to yet another web service.

First of all, you need one more web service method. Here is the code for a really simple update method. This code snippet doesn't actually update anything. It only captures updates sent to the server and saves them to a file. I like using this update method during development as it lets me ensure that my client-side Flash works properly, independent of any back-end processing. This function dumps any updates to a file named c:\test.xml, which receives updates in XML packets. You can change the path as necessary.

For now, add the following function to employees.cfc.

<CFFUNCTION NAME="Update"
            HINT="Update employee records"
            ACCESS="remote"
            RETURNTYPE="string">
   <CFARGUMENT NAME="deltaData"
               TYPE="string"
               REQUIRED="true">
   <CFFILE ACTION="write"
           ADDNEWLINE="no"
           FILE="c:\test.xml"
           OUTPUT="#ARGUMENTS.deltaData#">
   <CFRETURN "">
</CFFUNCTION>

You will also need to refresh the web service list in Flash by going to Window > Development Panels > Web Services. Click the refresh icon to update the web service with the new function. Note that you don't need to reregister your CFC and its functions every time you change them; you only need to do so when you have added or deleted a function from your ColdFusion component.

Once you have updated employees.cfc, follow these steps to implement a Resolver:

  1. Select the data form. You'll add two new components to it. These are not visual components, so you can put them anywhere. To keep things simple, add them to the bottom of the form where there is room.
  2. The Resolver tracks changes and prepares the delta packet, the XML packet that contains all changes for submission back to the server. Drag an RDBMSResolver component onto the data form (Figure 25).

    Resolvers have no UI and may be placed anywhere on the stage

    Figure 25. Resolver components have no UI; you can place them anywhere on the Stage.

  3. Open the Property inspector and name the new Resolver component instance userResolver.
  4. Open the Components Inspector panel; ensure that you have selected userResolver and select the Parameters tab.
  5. To track changes and report them correctly, you must specify the table column that is the data's primary key in the Resolver. The primary key for employee data is EMPLOYEEID. Click fieldInfo and press the magnifying glass button to display a Values dialog box.
  6. Click the Plus (+) button to add a field.
  7. Set the fieldname value to EMPLOYEEID, and the isKey value to true (Figure 26).

    The Resolver needs to know the name of the Primary Key to effectively track data changes

    Figure 26. The Resolver needs to know the name of the primary key to effectively track data changes.

  8. Select the Bindings tab in the Component Inspector panel.
  9. Click the Plus (+) button to display the Add Binding dialog box.
  10. Select deltaPacket and click OK.
  11. Bind the deltaPacket in empDataSet to the deltaPacket in userResolver. Be sure to select the correct DataSet as there are more than one (Figure 27). Click OK.

    The deltaPacket contains data changes until they are submitted to the server for processing

    Figure 27. The deltaPacket contains data changes until they are submitted to the server for processing

You've configured the Resolver to update a delta packet whenever a user changes the empDataSet. Next, you need to tell Flash what to do with these changes. This requires one more WebServiceConnector:

  1. Select the data form.
  2. Drag a WebServiceConnector component from the Components panel onto the Stage.
  3. Open the Property inspector and name the new WebServiceConnector instance userUpdateService.
  4. Open the Components Inspector panel and select the Parameters tab.
  5. In the WSDLURL field, select the URL for the employees.cfc web service. If you're using the defaults, this is http://localhost:8500/cfflash/employees.cfc?wsdl. In the operation field, select Update.
  6. The Update web service method requires that you pass a parameter to the delta packet; instead of using a binding, you pass this manually. This gives you better control when you pass it. Click the userResolver component instance on the Stage and enter the following code in the Actions panel:

    // Process updates
    on (beforeApplyUpdates) {
       // Pass delta packet to the Web Service
       _parent.userUpdateService.params = { deltaData:this.updatePacket };
       // Fire Web Service
       _parent.userUpdateService.trigger();
    }
    

Now you have a Resolver to track changes and a WebServiceConnector to send those changes to ColdFusion for processing. Now you need a Save button so you can save changes. Here's what you need to do:

  1. Select the navLogout form.
  2. Drag a Button control from the Components panel onto the Stage. In the Property inspector, name the instance buttonSave. Set W=75, H=22, X=180, Y=370. Click the label field and set it to Save.
  3. Open the Actions panel and enter the following code:

    // Process save button
    on (click) {
       _root.application.data.empDataSet.applyUpdates();
    }
    
  4. Save your changes and test the application. Now you can log in and edit, and then view the submitted changes in the ColdFusion-generated XML file at c:\test.xml.

Before we wrap up the Flash side of things, here are some final tweaks:

  1. When logging out, you should probably save any unsaved changes. Select the navLogout form and the Logout button and insert the following code into the on (click) block:

    // Are there any unsaved changes?
    if (_root.application.data.empDataSet.changesPending()) {
      // Yes, save them
      _root.application.data.empDataSet.applyUpdates();
    }
    
  2. Similarly, if a user edits data for one department, but then selects another department in the upper grid, you need to save changes. To do so, modify the code in the Actions panel for deptDataSet in the data form, changing it to the following:

    // Each time there is a department change
    on (iteratorScrolled) {
      // If there are unsaved changes
      if (_parent.empDataSet.changesPending()) {
        // Save them
        _parent.empDataSet.applyUpdates();
      }
      // Get employees
      _parent.empReceiveWebServiceConnector.trigger();
    }
    
  3. When the application first loads, the lower grid does not populate or display data until the user changes the department, which means that the first department does not display until the user deselects and selects it again. To fix this, add the following code to the Actions panel for deptDataSet, which is in the data form:

    // After department load get employees
    on (afterLoaded) {
      _parent.empReceiveWebServiceConnector.trigger();
    }
    

In truth, arbitrarily writing data to the server is probably not a good thing. In both of the above examples, you should probably display an alert box asking the user whether he wants to discard unsaved changes or not, but I'll leave working that out as homework for you.

Processing Updates

The Flash side of the application is complete, but what about the server side? Right now the application dumps changes to an XML file, but you need ColdFusion code to process the uploaded delta packets and update the databases.

The complete Update method, the one that actually updates the tables, is too lengthy to include here. You can download it from the sample files at the beginning of this tutorial, but I explain the key parts here.

The method received the delta packet from Flash as an argument:

<CFARGUMENT NAME="deltaData"
TYPE="string"
REQUIRED="true">

The code then parses the delta packet, and uses an XPath search to obtain an array of nodes. Each insert, delete, and update will be in its own node:

<!--- Parse received XML packet --->
<CFSET deltaXML=XMLParse(deltaData)>

<!--- Extract all nodes (each operation is a node) --->
<CFSET deltaNodes=XmlSearch(deltaXML, "update_packet/*")>

<!--- How many operations? --->
<CFSET nodeCount=ArrayLen(deltaNodes)>

The code then loops through from one to nodeCount to process each action. The following code is the first line within the loop, determining the action by looking at the node name:

<!--- Get action (INSERT UPDATE or DELETE) --->
<CFSET action=deltaNodes[i].XmlName>

If the action is an UPDATE or a DELETE then the logic requires the primary key. It uses another XPath search to find all fields with key set to true (this based on the field specified in the Resolver previously). Once processed, the variable pkid will contain the primary key value so that you can use it in constructed SQL statements:

<!--- Get primary key if update or delete --->
<CFIF (action IS "update") OR (action IS "delete")>
<!--- Get node with key field --->
<CFSET keyFldNodes=XmlSearch(deltaXML, "update_packet/*[#i#]/field[@key='true']")>
<!--- Get primary key (in "OldValue") --->
<CFSET pkid=keyFldNodes[1].XmlAttributes.oldValue>
</CFIF>

Then the application performs one XPath search per loop to obtain all the non-key fields, where key is false:

<!--- Now get all non-key fields --->
<CFSET modFldNodes=XmlSearch(deltaXML, "update_packet/*[#i#]/field[@key='false']")>

Armed with all this information, the code can construct a SQL statement:

  • For UPDATE statements, the logic creates the opening SQL, appends each name=value pair, and finally adds the WHERE clause.
  • For DELETE statements, the logic generates a simple DELETE using the retrieved primary key.
  • For INSERT statements, the logic populates two lists that contain field names and values, generates a new primary key (a UUID), and generates the complete SQL INSERT statement.

At the bottom of the loop, the logic appends the new SQL statement to an array of SQL statements:

<!--- Add this statement to the array of SQL statements --->
<CFSET ArrayAppend(sqlStatements, sql)>

Then it creates a CFTRANSACTION tag block that contains CFLOOP tag which loops over the array and submits a SQL query for each entry, as follows:

<!--- And run the query --->
<CFQUERY DATASOURCE="exampleapps">
#PreserveSingleQuotes(sql)#
</CFQUERY>

The method invoked by the Resolver expects a result packet. (This could contain error messages if specific SQL statements failed, or other information that could be used by Flash on the client.) For simplicity's sake, the CFC method in this example returns an empty packet:

<!--- Return result packet (this one is empty) --->
<CFRETURN "<result_packet />">

Now ColdFusion can process the delta packet and update the database in a single transaction.

Summary

And there you have it: a complete client-server application—the client in Flash and the server in ColdFusion—oh, and the entire application is under 150K at runtime! While I covered a lot of concepts and ideas in this article, the truth is that is does not get much more complex than this. Most of what you'll need to do when building your own ColdFusion/Flash applications will be similar to what you did here today.

There is definitely a learning curve here, especially for those of us who have feared Flash thus far. But as you can see by the finished product, the investment is well worth it.

Where To Go From Here

You now have a complete working application, an impressive and useful example of ColdFusion and Flash working together to create a better user experience. If you'd like to experiment further, here are some suggested application enhancements:

  • As already noted above, the employee data grid should not really display the EMPLOYEEID and DEPTIDFK columns. You can run the DataGrid Column Editor wizard to correct this.
  • The tables contain additional employee information that does not display in the grid (including a notes field). You may want to change the screen layout so that the department grid is on the left (make it narrower than it is now), the employees grid on the top right, and a selected employee's details on the bottom right. To display the additional details you'd need to add controls to display employee details, and then bind each control to the employee data set. You'd also want to list the extra columns in the Data Connection Wizard (and then use the DataGrid Column Editor to prevent them from displaying).
  • Right now, a user edits within the employee data grid, but what if the user wanted to edit other columns not displayed in the grid? You may want to add an Edit button to the navLogout page, and have it pop-up an edit form (which a user could use in addition to quick inline editing). You'd need to create a new form, populate it with controls, and bind them to a new CFC method to update the employee. Or you could combine this idea with the previous bullet for employee detail controls, and allow users to edit those if they're logged in.
  • The Update()method may succeed or fail, but ColdFusion doesn't return success or failure notifications. You may want change Update() method so that it builds an XML result packet which it sends to Flash. You could then trap the web wervices on (result) event and inspect the returned packet, displaying a notification window if for some reason the Update() method fails.
  • While this app works, there is an inherent security hole; you should not deploy this application as it is on a public facing site. The CFC Update() method accepts a deltaPacket with updates. In our example that packet comes from client-side Flash, but if hackers were aware of the CFC and the format of the deltaPacket, they could submit packets of their own. The solution to this is to use server-side session-state management so that the log-on is not just an on/off state which swaps forms and makes grids editable, but rather, the CFC remembers logged in users and only accepts Update() requests from them.

As you can see, there are lots of possibilities and opportunities. To learn more you may want to take a look at these resources:


About the author

Ben Forta is the Macromedia senior product evangelist and the author of numerous books, including ColdFusion Web Application Construction Kit and its sequel Advanced ColdFusion Application Development, as well as books on SQL, JavaServer Pages, WAP, Windows development, and more. Ben co-authored the official Macromedia ColdFusion training material, the certification tests and Macromedia Press study guides for those tests, now spends a considerable amount of time lecturing, speaking, and writing about application development worldwide.